import React, { Component } from 'react';
import {
  View,
  Text,
  StyleSheet,
  DeviceEventEmitter,
  TouchableNativeFeedback,
  Image,
  Dimensions,
  FlatList,
  Alert,
} from 'react-native';
import * as request from '../../services/pollingRequest';
import { UtilToast } from '../../utils/util-method';
import Theme from '../../native-base-theme/variables/commonColor';
import LineItem from '../../components/detail/lineItem';
import ZlstIcon from '../../components/zlst-icons';
import { PollingItem } from '../../components/polling';

const deviceWidth = Dimensions.get('window').width;
class Task extends Component {
  static navigationOptions = {
    title: '点巡检任务详情',
    headerStyle: { backgroundColor: Theme.toolbarDefaultBg },
    headerTintColor: '#FFFFFF',
    headerTitleStyle: {
      fontWeight: 'bold',
      fontSize: 20,
      flex: 1,
      textAlign: 'center',
    },
    headerBackImage: (
      <ZlstIcon
        name="fanhui"
        size={24}
        color="white"
      />
    ),
    headerRight: <View />,
  }

  refreshEvt = null;

  constructor(props) {
    super(props);
    this.state = {
      checkDate: '',
      checkEquipmentVOs: [],
      checkOrgName: null,
      checkStaffName: '',
      checkType: '',
      checkTypeName: '',
      checkUserCode: '',
      checkrecordId: '',
      startTime: '',
      status: '',
      statusName: '',
    };
  }

  componentWillMount() {
    this._getTaskInfo();
    this.refreshEvt = DeviceEventEmitter.addListener('taskRerfesh', this.refreshPage);
  }

  componentWillUnmount() {
    if (this.refreshEvt) {
      this.refreshEvt.remove();
      this.refreshEvt = null;
    }
  }

  refreshPage = () => {
    this._getTaskInfo(this.state.checkrecordId);
  }

  _getTaskInfo = async (id) => {
    try {
      DeviceEventEmitter.emit('showLoading', true);
      const checkrecordId = id || this.props.navigation.state.params.checkrecordId;
      const resp = await request.getTaskInfo(checkrecordId);
      DeviceEventEmitter.emit('showLoading', false);
      if (resp.resultCode == '0') {
        this.setState({
          ...resp.data,
        });
      } else {
        UtilToast(resp.resultMsg || '查询错误，请重试！', 'danger');
      }
    } catch (error) {
      DeviceEventEmitter.emit('showLoading', false);
      console.log(error);
    }
  }

  _toQrCode = () => {
    global.navigation.navigate({
      routeName: 'Qrcode',
      params: {
        flag: 'task',
        checkrecordId: this.state.checkrecordId,
      },
    });
  }

  _taskOver = () => {
    Alert.alert(
      '提示',
      '是否结束巡检任务',
      [
        {
          text: '否',
          style: 'cancel',
          onPress: () => {
          },
        },
        {
          text: '是',
          onPress: () => {
            this.finishTask();
          },
        },
      ],
    );
  }

  finishTask = async () => {
    try {
      DeviceEventEmitter.emit('showLoading', true);
      const resp = await request.finishTask(this.state.checkrecordId);
      DeviceEventEmitter.emit('showLoading', false);
      if (resp.resultCode == '0') {
        UtilToast('操作成功！', 'success');
        if (this.props.navigation.state && this.props.navigation.state.params && this.props.navigation.state.params.routeKey) {
          global.navigation.goBack(this.props.navigation.state.params.routeKey || undefined);
          DeviceEventEmitter.emit('refreshTaskPageEvent');
        } else {
          this.props.navigation.goBack();
          DeviceEventEmitter.emit('refreshTaskPageEvent');
        }
        // global.navigation.goBack(this.props.navigation.state.params.routeKey || undefined);
      } else {
        UtilToast(resp.resultMsg || '查询错误，请重试！', 'danger');
      }
    } catch (error) {
      DeviceEventEmitter.emit('showLoading', false);
      console.log('error', error);
    }
  }

  _itemClick = (data) => {
    console.log('task page, ', data);
    global.navigation.navigate({
      routeName: 'TaskDeviceDetail',
      params: {
        equipcheckId: data.item.equipcheckId,
        equipmentCode: data.item.equipmentCode,
        equipmentName: data.item.equipmentName,
      },
    });
  }

  _itemRender = data => (
    <PollingItem
        data={data}
        fileds={{
          firstLineFiled: 'resultName',
          secondLineFiled: 'equipmentName',
          thridLineFiled: 'createTime',
        }}
        onClick={() => { this._itemClick(data); }}
      />
  )

  _getListContent = () => {
    const { checkEquipmentVOs } = this.state;
    if (checkEquipmentVOs && !checkEquipmentVOs.length) {
      return (
        <View>
          <Text
            style={{
              color: '#ffffff',
              fontSize: 16,
              textAlign: 'center',
            }}
          >
            暂无数据
          </Text>
        </View>
      );
    }
    return (
      <FlatList
        showsVerticalScrollIndicator={false}
        data={checkEquipmentVOs}
        renderItem={item => this._itemRender(item)}
        keyExtractor={(item, index) => item + index}
      />
    );
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={{ flex: 1 }}>
          <LineItem item={{ label: '巡检人', value: this.state.checkStaffName }} />
          <LineItem item={{ label: '巡检班组', value: this.state.checkOrgName || global.user.organization.name }} />
          <LineItem item={{ label: '巡检日期', value: this.state.checkDate }} />
          <LineItem item={{ label: '巡检类型', value: this.state.checkTypeName }} />
          <LineItem item={{ label: '任务状态', value: this.state.statusName }} />
          <View style={styles.equListContianer}>
            <View style={styles.header}>
              <Text style={{ color: '#ffffff' }}>巡检设备列表</Text>
              {this.state.status == '1' && (
                <ZlstIcon
                  onPress={this._toQrCode}
                  name="saoma"
                  size={24}
                  color="white"
                />
              )}
            </View>
            <View style={styles.content}>
              {this._getListContent()}
            </View>
          </View>
        </View>
        { this.state.status == '1'
          && (
          <View>
            <Image
              source={require('../../../assets/images/btn-cut-line-xxx.png')}
              style={{ width: deviceWidth, height: 2, alignItems: 'center' }}
              resizeMode="stretch"
              resizeMethod="auto"
            />
            <View style={styles.operationBtns}>
              <TouchableNativeFeedback
                onPress={this._taskOver}
                key={1}
              >
                <View style={{ flex: 1 }}>
                  <Text style={styles.btnText}>巡检结束</Text>
                </View>
              </TouchableNativeFeedback>
            </View>
          </View>
          )}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    width: '100%',
    height: '100%',
    backgroundColor: Theme.myPrimary,
    paddingLeft: 20,
    paddingRight: 20,
    paddingTop: 10,
  },
  header: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  equListContianer: {
    flex: 1,
  },
  content: {
    flex: 1,
  },
  operationBtns: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  btnText: {
    textAlign: 'center',
    color: '#ffffff',
    paddingTop: 15,
    paddingBottom: 15,
  },
});

export default Task;
